﻿@{
    ViewBag.Title = "UpdateAbsenceNullCode"; 

    using (var db = new GERPContext(true))
    {  
        foreach(var absence in db.PsAbsences.ToList())
        {

            string strCodeDate = new System.Globalization.ThaiBuddhistCalendar().GetYear(absence.CreatedWhen.Value).ToString().Substring(2);
            strCodeDate += absence.CreatedWhen.Value.ToString("MM");
            string strPrefix = "AB"; 
            string strMaxCode = db.PsAbsences.ToList().Where(m => (m.Code != null ? m.Code : "").StartsWith(strPrefix + strCodeDate)).Max(m => m.Code);
            string strResult = null;
            if(string.IsNullOrWhiteSpace(strMaxCode))
            {
                strResult = strPrefix + strCodeDate + "0001";
            } else
            {
                var strRunning = strMaxCode.Substring(strMaxCode.Length - 4);
                int nRunning;
                if (int.TryParse(strRunning, out nRunning))
                {
                    strResult = strPrefix + strCodeDate + (nRunning + 1).ToString("0000");
                }
                else
                {
                    strResult = strPrefix + strCodeDate + "0001";
                }
            }
            absence.Code = strResult;
        }
        db.SaveChanges();
    }
}